package com.example.zzx.dovebook.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;

import com.example.baselibrary.net.HttpHelper;
import com.example.baselibrary.net.RetrofitProcessor;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.util.Iterator;
import java.util.Stack;

public class BaseApplication extends Application {


    private Stack<Activity> mActivityStack;

    private static Handler sMainHandler;

    private static Context sContext;

    @Override
    public void onCreate() {
        super.onCreate();
        sMainHandler = new Handler();

        sContext = getApplicationContext();

        mActivityStack = new Stack<>();

        registerActivityLifecycleCallbacks(mCallbacks);

        HttpHelper.getInstance().init(new RetrofitProcessor());

        ZXingLibrary.initDisplayOpinion(this);
    }

    public void exitApp() {
        Iterator<Activity> iterator = mActivityStack.iterator();
        while (iterator.hasNext()) {
            iterator.next().finish();
        }
    }

    public static Handler getMainHandler() {
        return sMainHandler;
    }

    public static Context getContext() {
        return sContext;
    }

    private ActivityLifecycleCallbacks mCallbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            mActivityStack.push(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            if (mActivityStack.contains(activity)) {
                mActivityStack.remove(activity);
            }
        }
    };
}
